package com.ruoyi.system.controller;

import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ArrayUtil;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.Student;
import com.ruoyi.system.service.IStudentService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2022-12-08
 */
@RestController
@RequestMapping("/system/student")
public class StudentController extends BaseController {
    @Autowired
    private IStudentService studentService;
    @Autowired
    private ISysUserService userService;

    /**
     * 查询【请填写功能名称】列表
     */
    // @PreAuthorize("@ss.hasPermi('system:student:list')")
    @GetMapping("/list")
    public TableDataInfo list(Student student) {
        startPage();
        List<Student> list = studentService.selectStudentList(student);
        return getDataTable(list);
    }

    /**
     * 导出【请填写功能名称】列表
     */
    @PreAuthorize("@ss.hasPermi('system:student:export')")
    @Log(title = "导出", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Student student) {
        List<Student> list = studentService.selectStudentList(student);
        ExcelUtil<Student> util = new ExcelUtil<Student>(Student.class);
        util.exportExcel(response, list, "【请填写功能名称】数据");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:student:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(studentService.selectStudentById(id));
    }

    /**
     * 新增【请填写功能名称】
     */
    // @PreAuthorize("@ss.hasPermi('system:student:add')")
    @Anonymous
    @Log(title = "新增学生", businessType = BusinessType.INSERT)
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult add(@RequestBody Student student) {
        SysUser user = new SysUser();
        user.setNickName(student.getName());
        user.setUserName(student.getSno());
        user.setStatus(student.getStatus());
        user.setPassword(SecurityUtils.encryptPassword(student.getPassword()));
        Long[] roldIds = new Long[]{100L};
        user.setRoleIds(roldIds);
        if (BeanUtil.isNotEmpty(userService.selectUserByUserName(student.getSno()))) {
            return error("新增用户'" + user.getUserName() + "'失败，用户名已存在");
        }
        userService.insertUser(user);
        return toAjax(studentService.insertStudent(student));
    }

    /**
     * 修改【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:student:edit')")
    @Log(title = "编辑学生", businessType = BusinessType.UPDATE)
    @PutMapping
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult edit(@RequestBody Student student) {
        SysUser user = userService.selectUserByUserName(student.getSno());
        Assert.notNull(user,"数据为空");
        user.setNickName(student.getName());
        user.setUserName(student.getSno());
        user.setStatus(student.getStatus());
        user.setPassword(SecurityUtils.encryptPassword(student.getPassword()));
        Long[] roldIds = new Long[]{100L};
        user.setRoleIds(roldIds);
        // if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user))) {
        //     return error("该用户'" + user.getUserName() + "'失败，学号已存在");
        // }
        userService.updateUser(user);
        return toAjax(studentService.updateStudent(student));
    }

    @Anonymous
    @Log(title = "修改密码", businessType = BusinessType.UPDATE)
    @PutMapping("/password")
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult editPassword(@RequestBody Student student) {
        SysUser user = userService.selectUserByUserName(SecurityUtils.getUsername());
        Assert.notNull(user,"数据为空");
        if (!SecurityUtils.matchesPassword(student.getPassword(),user.getPassword())) {
            return AjaxResult.error("原密码错误！！！");
        }
        user.setPassword(SecurityUtils.encryptPassword(student.getNewPassword()));
        Long[] roldIds = new Long[]{100L};
        user.setRoleIds(roldIds);
        userService.updateUser(user);
        student.setSno(user.getUserName());
        student.setPassword(student.getNewPassword());
        return toAjax(studentService.updateStudentBySno(student));
    }
    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:student:remove')")
    @Log(title = "批量删除学生", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        Assert.notEmpty(ids,"请至少选中一条数据");
        List<Student> list = studentService.selectStudentListByIds(ids);
        for (Student student : list) {
            SysUser sysUser = userService.selectUserByUserName(student.getSno());
            userService.deleteUserById(sysUser.getUserId());
        }
        return toAjax(studentService.deleteStudentByIds(ids));
    }
}
